<?php
/**
* 用户收益模块Api Service
*
* 用户收益模块Api Service的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Statistics;

use Log;

use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\GeneralTool;
use App\Services\UserService\UserTool;
use App\Services\Tool\Statistics\IncomeTool;
use App\Services\Tool\Statistics\UserBankTool;
use App\Services\Tool\Pay\UnionPayTool;
use App\Services\Tool\Pay\UnionChinaPay;

class IncomeApi{

    function __construct(UserTool $userTool,
                         IncomeTool $incomeTool,
                         UserBankTool $userBankTool,
                         UnionPayTool $unionTool,
                         UnionChinaPay $union){
        $this->userTool = $userTool;
        $this->incomeTool = $incomeTool;
        $this->userBankTool = $userBankTool;
        $this->unionTool = $unionTool;
        $this->union = $union;
    }

    /**
        收益趋势
        参数：
            user_id     用户编号
     */
    function myIncomes($input){
        //判断参数是否足够
        if(!isset($input['user_id'])) return GeneralTool::createResult('','M00002');
        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $money = $this->userTool->getBalance($input['user_id']);
        $arr['balance'] = isset($money['balance'])?$money['balance'].'':'0';
        $arr['total_income'] = isset($money['total_revenue'])?$money['total_revenue'].'':'0';
        $arr['freeze_balance'] = $this->incomeTool->getUserBalanceFreeze(['user_id'=>$input['user_id'],'state'=>1]);
        $arr['withdraw_fee'] = $this->incomeTool->getUserBalanceWithdraw(['user_id'=>$input['user_id'],'state'=>2,'result'=>1]);
        $arr['balance'] += $arr['freeze_balance'];
        $arr['balance']  = GeneralTool::priceFormat($arr['balance']);

        $arr['product'] = env('INCOME_DRAW').'type=product&user_id='.$input['user_id'];
        $arr['source']  = env('INCOME_DRAW').'type=source&user_id='.$input['user_id'];

        return GeneralTool::createResult($arr,'M00000');
    }


    /**
        图表
        参数：
            user_id         用户编号
            type            类型  source素材 product商品
     */
    function draw($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||!isset($input['type'])) return GeneralTool::createResult('','M00002');
        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');
        //图表数据
        $arr = $this->incomeTool->getUserIncomes(['user_id'=>$input['user_id'],'type'=>$input['type']]);
        return GeneralTool::createResult($arr,'M00000');
    }

    /**
        收益明细
        参数：
            user_id         用户编号
            page            页码
            per_page        每页显示数量
     */
    function incomeStatement($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||!isset($input['page'])||!isset($input['per_page'])) return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = is_numeric($input['per_page'])?$input['per_page']:10;
        //data
        $result = $this->incomeTool->incomeStatement(['user_id'=>$input['user_id'],'change_type'=>1,'type'=>'income','state'=>1],$input['per_page']);

        $money                    = $this->userTool->getBalance($input['user_id']);
        $result['balance']        = isset($money['balance'])?$money['balance'].'':'0';
        $result['total_income']   = isset($money['total_revenue'])?$money['total_revenue'].'':'0';
        $result['freeze_balance'] = $this->incomeTool->getUserBalanceFreeze(['user_id'=>$input['user_id'],'state'=>1]);
        $result['balance']        += $result['freeze_balance'];
        $result['balance']        = GeneralTool::priceFormat($result['balance']).'';
        $result['withdraw_fee']   = $this->incomeTool->getUserBalanceWithdraw(['user_id'=>$input['user_id'],'state'=>2,'result'=>1]);


        return GeneralTool::createResult($result,'M00000');
    }

    /**
        提现明细
        参数：
            user_id         用户编号
            page            页码
            per_page        每页显示数据量
     */
    function withdrawStatement($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||!isset($input['page'])||!isset($input['per_page'])) return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['per_page'] = is_numeric($input['per_page'])?$input['per_page']:10;
        //data
        $result = $this->incomeTool->withdrawStatement(['user_id'=>$input['user_id'],'per_page'=>$input['per_page']]);
        $money = $this->userTool->getBalance($input['user_id']);
        $result['balance']        = isset($money['balance'])?$money['balance'].'':'0';
        $result['total_income']   = isset($money['total_revenue'])?$money['total_revenue'].'':'0';
        $result['freeze_balance'] = $this->incomeTool->getUserBalanceFreeze(['user_id'=>$input['user_id'],'state'=>1]);
        $result['withdraw_fee']   = $this->incomeTool->getUserBalanceWithdraw(['user_id'=>$input['user_id'],'state'=>2,'result'=>1]);
        $result['balance']        += $result['freeze_balance'];

        return GeneralTool::createResult($result,'M00000');
    }

    /**
        获取申请提现页数据
        参数：
            user_id     用户编号
     */
    function getDataByApplyWithdraw($input){
        //判断参数是否足够
        if(!isset($input['user_id'])) return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $money = $this->userTool->getBalance($input['user_id']);
        $arr['balance']        = isset($money['balance'])?$money['balance'].'':'0';
        $arr['bank_card']      = $this->userBankTool->getUserBankCard(['user_id'=>$input['user_id'],'state'=>1]);
        $arr['poundage']       = IncomeTool::get_poundage();
        $arr['withdraw_max']   = IncomeTool::get_withdraw_max();
        $arr['freeze_balance'] = $this->incomeTool->getUserBalanceFreeze(['user_id'=>$input['user_id'],'state'=>1]);
        $arr['has_password']   = UserBankTool::user_has_withdraw_password($input) ? 0 : 1;

        return GeneralTool::createResult($arr,'M00000');
    }

    /**
        申请提现
        参数：
            user_id         用户编号
            user_card_id    用户银行卡编号
            total_fee       金额
     */
    function applyWithdraw($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||!isset($input['user_card_id'])) return GeneralTool::createResult('','M00002');

        //判断金额格式是否正确
        $withdraw_max   = IncomeTool::get_withdraw_max();
        if(!is_numeric($input['total_fee']) || $input['total_fee'] <= 0 || $input['total_fee'] > $withdraw_max){
            $re = GeneralTool::createResult('','M06017');
            $re['message'] .= '提现金额区间: ¥ 0---' . $withdraw_max;
            return $re;
        }

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        /**
        $times = $this->incomeTool->user_can_apply_withdraw($input['user_id']);
        if($times['state'] != 'M00000') return $times;
        */

        //获取银行卡信息
        $card = $this->userBankTool->getUserBankCard(['user_id'=>$input['user_id'],'id'=>$input['user_card_id'],'state'=>1]);

        if(!isset($card->result)) return GeneralTool::createResult('','M06016');
        if($card->result!=2) return GeneralTool::createResult('','M06020');

        $money            = $this->userTool->getBalance($input['user_id']);
        $input['balance'] = isset($money['balance']) ? $money['balance'].'' : '0' ;
        $poundage         = IncomeTool::get_poundage();
        if($input['total_fee'] + $poundage > $input['balance']) return GeneralTool::createResult('','M06018');

        $input['total_fee'] = sprintf('%.2f',$input['total_fee']);

        try{

            //修改余额
            $change = $this->userTool->changeBalance($input['user_id'],0 - $input['total_fee'] - $poundage);
            if($change==0) return GeneralTool::createResult('','M00001');
            //申请提现
            $result  = $this->incomeTool->applyWithdraw(['user_id'      => $input['user_id'],
                                                         'bank_card_no' => $card->bank_card_no,
                                                         'bank_branch'  => $card->bank_branch,
                                                         'bank_name'    => $card->bank_name,
                                                         'card_holder'  => $card->card_holder,
                                                         'phone'        => $card->phone,
                                                         'total_fee'    => $input['total_fee'],
                                                         'prov'         => $card->prov,
                                                         'city'         => $card->city,
                                                         'poundage'     => $poundage]);
            if($result==0) Throw new Exception('申请提现异常');
            //推送
            $this->incomeTool->submit_apply_withdraw_push(['user_id'   => $input['user_id'],
                                                           'bank_name' => $card->bank_name,
                                                           'total_fee' => $input['total_fee']]);

            $money = $this->userTool->getBalance($input['user_id']);
            $arr['balance'] = isset($money['balance'])?$money['balance'].'':'0';
            return GeneralTool::createResult($arr,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00001');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        获取申请提现页数据
        参数：
            user_id     用户编号
     */
    function apply_withdraw_page($input){
        //判断参数是否足够
        if(!isset($input['user_id'])) return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $money = $this->userTool->getBalance($input['user_id']);
        $arr['balance']        = isset($money['balance'])?$money['balance'].'':'0';
        $arr['bank_card']      = $this->userBankTool->getUserBankCard(['user_id'=>$input['user_id'],'state'=>1]);
        $arr['poundage']       = IncomeTool::get_poundage();
        $arr['withdraw_max']   = IncomeTool::get_withdraw_max();
        $freeze_balance        = $this->incomeTool->getUserBalanceFreeze(['user_id'=>$input['user_id'],'state'=>1]);

        return GeneralTool::createResult($arr,'M00000');
    }

    /**
        申请提现
        参数：
            user_id         用户编号
            user_card_id    用户银行卡编号
            total_fee       金额
            password        密码
     */
    function apply_withdraw_new($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||!isset($input['user_card_id']) || !isset($input['password'])) return GeneralTool::createResult('','M00002');
        if(!isset($input['total_fee']) || !is_numeric($input['total_fee'])) return GeneralTool::createResult('', 'M06017');

        //判断金额格式是否正确
        $withdraw_max   = IncomeTool::get_withdraw_max();
        if($input['total_fee'] <= 0 || $input['total_fee'] > $withdraw_max){
            $re = GeneralTool::createResult('','M06017');
            $re['message'] .= '提现金额区间: ¥ 0---' . $withdraw_max;
            return $re;
        }

        //判断用户是否存在
        if(UserTool::getPhoneByUserid($input['user_id']) == '')
            return GeneralTool::createResult('', 'M06027');

        if(UserBankTool::user_has_withdraw_password($input))
            return GeneralTool::createResult('','M06036');

        if(UserBankTool::verfy_withdraw_password($input) == 0)
            return GeneralTool::createResult('','M06035');

        if(userBankTool::user_fail_count($input) >= env('VERFY_FAIL_TIME'))
            return GeneralTool::createResult('', 'M06033');
        /**
        $times = $this->incomeTool->user_can_apply_withdraw($input['user_id']);
        if($times['state'] != 'M00000') return $times;
        */

        //获取银行卡信息
        $card = $this->userBankTool->getUserBankCard(['user_id'=>$input['user_id'],'id'=>$input['user_card_id'],'state'=>1]);

        if(!isset($card->result)) return GeneralTool::createResult('','M06016');
        if($card->result!=2) return GeneralTool::createResult('','M06020');

        $money            = $this->userTool->getBalance($input['user_id']);
        $input['balance'] = isset($money['balance']) ? $money['balance'].'' : '0' ;
        $poundage         = IncomeTool::get_poundage();
        if($input['total_fee'] + $poundage > $input['balance']) return GeneralTool::createResult('','M06018');

        $input['total_fee'] = sprintf('%.2f',$input['total_fee']);

        try{

            //修改余额
            $change = $this->userTool->changeBalance($input['user_id'],0 - $input['total_fee'] - $poundage);
            if($change==0) return GeneralTool::createResult('','M00001');
            //申请提现
            $result  = $this->incomeTool->applyWithdraw(['user_id'      => $input['user_id'],
                                                         'bank_card_no' => $card->bank_card_no,
                                                         'bank_branch'  => $card->bank_branch,
                                                         'bank_name'    => $card->bank_name,
                                                         'card_holder'  => $card->card_holder,
                                                         'phone'        => $card->phone,
                                                         'total_fee'    => $input['total_fee'],
                                                         'prov'         => $card->prov,
                                                         'city'         => $card->city,
                                                         'poundage'     => $poundage]);
            if($result==0) Throw new Exception('申请提现异常');
            //推送
            $this->incomeTool->submit_apply_withdraw_push(['user_id'   => $input['user_id'],
                                                           'bank_name' => $card->bank_name,
                                                           'total_fee' => $input['total_fee']]);

            $money = $this->userTool->getBalance($input['user_id']);
            $arr['balance'] = isset($money['balance'])?$money['balance'].'':'0';
            UserBankTool::set_bank_card_default($input);
            return GeneralTool::createResult($arr,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00001');
        }finally{
            SQL::FinallyDo();
        }
    }

    function test($input){
        $result = $this->union->test();
        return $result;
    }

}
